package apis

import (
	"bytes"
	"encoding/json"
	"errors"
	"gopin/db"
	"gopin/logger"
	"io"
	"net/http"
	"strings"
	"time"

	"gorm.io/gorm"
)

type Apis struct {
	client *http.Client
}

func NewApis() *Apis {
	return &Apis{
		client: &http.Client{},
	}
}

// GetApiGroups 获取所有 API 分组
func (a *Apis) GetApiGroups() []*db.ApiGroup {

	return db.FindAllApiGroups()
}

// AddApiGroup 添加新的 API 分组
func (a *Apis) AddApiGroup(name string, parentId uint) error {
	logger.Info("添加分组000", "name", name, "parentId", parentId)

	// 验证名称不能为空
	if name == "" {
		return errors.New("分组名称不能为空")
	}
	// 检查名称是否重复
	group := db.FindApiGroupByName(name)
	if group.ID > 0 {
		return errors.New("分组名称已存在")
	}
	logger.Info("添加分组1", "name", name, "parentId", parentId)
	// 创建新分组
	now := time.Now()
	group = &db.ApiGroup{
		Name:      name,
		Sort:      999,
		ParentID:  parentId,
		CreatedAt: now,
		UpdatedAt: now,
	}
	logger.Info("添加分组2", "name", name, "parentId", parentId)
	group.Save()
	return nil
}

// RemoveApiGroup 删除 API 分组
func (a *Apis) RemoveApiGroup(id int64) error {
	group := db.FindApiGroupById(id)
	if group == nil {
		return errors.New("未找到指定的分组")
	}
	db.DeleteApiGroup(group)
	return nil
}

type ApiRequest struct {
	ID      int64
	Method  string
	Url     string
	Headers map[string]string
	Params  map[string]interface{}
	Cookies map[string]string
	Auth    struct {
		Type  string
		Token string
	}
	Body struct {
		Type string
		Raw  string
	}
	Intro string
}

type ApiResponse struct {
	StatusCode  int
	Message     string
	Headers     map[string]string
	ContentType string
	Data        string
}

// 执行 API 请求
func (a *Apis) SendRequest(req *ApiRequest) *ApiResponse {
	logger.Info("执行 API 请求", "req", req)
	request, err := http.NewRequest(req.Method, req.Url, bytes.NewBuffer([]byte(req.Body.Raw)))
	if err != nil {
		logger.Error("创建请求失败", "err", err)
		return nil
	}
	for key, value := range req.Headers {
		request.Header.Set(key, value)
	}
	resp, err := a.client.Do(request)
	if err != nil {
		logger.Error("执行请求失败", "err", err)
		return nil
	}
	defer resp.Body.Close()

	// 读取响应体
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		logger.Error("读取响应体失败", "err", err)
		return nil
	}

	// 解析响应数据
	var data interface{}
	if err := json.Unmarshal(body, &data); err != nil {
		// 如果不是 JSON，就返回字符串
		data = string(body)
	}

	headers := make(map[string]string)
	for key, value := range resp.Header {
		headers[key] = strings.Join(value, ",")
	}
	// 返回完整的响应信息，包括头部
	return &ApiResponse{
		StatusCode: resp.StatusCode,
		Headers:    headers, // 这里包含了完整的响应头
		Data:       string(body),
	}
}

// GetApis 获取指定分组下的所有 API
func (a *Apis) GetApis(groupId uint) ([]*db.Api, error) {
	apis := db.FindApisByGroupId(groupId)
	if apis == nil {
		return []*db.Api{}, nil
	}
	return apis, nil
}

// AddApi 添加新的 API
func (a *Apis) AddApi(api *db.Api) string {
	if api.Name == "" {
		return "API 名称不能为空"
	}
	if api.Method == "" {
		return "请求方法不能为空"
	}
	if api.URL == "" {
		return "请求 URL 不能为空"
	}
	now := time.Now()
	api.CreatedAt = now
	api.UpdatedAt = now
	err := api.Save()
	if err != nil {
		return err.Error()
	}
	return ""
}

func (a *Apis) SaveApi(api *db.Api) error {
	return api.Save()
}

func (a *Apis) DeleteApi(id uint) error {
	api := db.Api{Model: gorm.Model{ID: id}}
	return api.Delete()
}

// GetApiDetail 获取 API 详细信息
func (a *Apis) GetApiDetail(id uint) *db.Api {
	api := &db.Api{}
	return api.LoadById(id)
}
